<template>
    <el-space :fill="false">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="startInsert('/')"
        ></el-button>
        <el-input
            placeholder="请输入查询字符"
            clearable
            :prefix-icon="Search"
            v-model="searchPrefix"
        />
        <el-button type="primary" icon="Search" @click="search()"></el-button>
    </el-space>

    <el-table
        stripe
        :show-header="false"
        :data="tableData"
        row-key="key"
        @row-click="handleRowClick"

    >
        <!--    <el-table-column type="selection" width="55" :selectable="selectable" />-->
        <!--    <el-table-column prop="key" label="key" hidden="hidden" />-->
        <el-table-column prop="name" label="name" min-width="180">
            <template #default="scope">
                <el-space v-if="scope.row.dir">
                    <el-icon><Folder/></el-icon>
                    <span >{{ scope.row.name }}</span>
                </el-space>
                <el-space v-if="!scope.row.dir">
                    <el-icon ><Document/></el-icon>
                    <span >{{ scope.row.name }}</span>
                </el-space>
            </template>
        </el-table-column>
        <!--      <el-table-column prop="value" label="value" />-->
        <!--      <el-table-column prop="createdIndex" label="created" />-->
        <!--      <el-table-column prop="modifiedIndex" label="modified" />-->
        <el-table-column label="Operations" min-width="120" align="right">
            <template #default="scope">
                <el-button link type="primary" size="small" icon="View" @click="startDetail(scope.row)"
                           :disabled=scope.row.dir></el-button>
                <el-button link type="primary" size="small" icon="Plus" @click="startInsert(scope.row.key)"
                           :disabled=!scope.row.dir></el-button>
                <!--          <el-button link type="primary" size="small" icon="Edit" @click="startEdit(scope.row)" :disabled=scope.row.dir ></el-button>-->
                <el-button link type="primary" size="small" icon="Delete" @click="startDelete(scope.row)"></el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog
        v-model="insertDialog"
        title="新增/编辑节点信息"
        width="500"
    >
        <el-form :model="insertForm">
            <el-form-item v-if="insertForm.showName" label="name" prop="name">
                <el-input v-model="insertForm.name" placeholder="当前目录下添加子节点, 多级目录用 / 分隔">
                    <template #prepend>{{ insertForm.prefix }}</template>
                </el-input>
            </el-form-item>
            <el-form-item v-if="insertForm.showDir" label="isDir" prop="dir">
                <el-switch v-model="insertForm.dir"/>
            </el-form-item>
            <el-form-item label="value" prop="value" v-if="!insertForm.dir">
                <el-input v-model="insertForm.value" placeholder="示例 htt8080 "/>
            </el-form-item>
            <el-form-item label="ttl(s)" prop="ttl">
                <el-input v-model="insertForm.ttl" placeholder="过期时间"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <el-button @click="insertDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmInsert">确定</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, ref, h, defineProps} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import {cluster_version, etcd_keys_list, etcd_keys_post, etcd_keys_delete, etcd_keys_put,etcd_dir_delete} from "@/api/etcd2.js"
import {Search} from "@element-plus/icons-vue";
import {JsHelper} from "@/utils/js-helper.js"

const props = defineProps({
    connect: {
        type: Object,
        default: {
            name: '默认标题',
            url: 'http://127.0.0.1:2379',
            version: 'v2',
            username: 'root',
            password: '123456'
        }
    }
})

const emit = defineEmits(['click-row']);
const handleRowClick = (row, column, event) => {
    emit('click-row', row);
};

const startDetail = (row) => {
    emit('click-row', row);
}

// const store = useEtcdStore()
interface Node {
    dir?: boolean
    key: string
    name: string
    value: string
    ttl: string
    createdIndex: string
    modifiedIndex: string
    // hasChildren?: boolean
    children?: Node[]
}
const tableData = ref([])


/********* 新增 ********/
const insertDialog = ref(false)
const insertForm = ref({
    prefix: '',
    showName: true,
    name: '',
    showDir: true,
    dir: false,
    value: '',
    ttl: null,
})

function startInsert(prefix) {
    insertForm.value.prefix = prefix;
    insertForm.value.showName = true;
    insertForm.value.name = '';
    insertForm.value.showDir = true;
    insertForm.value.dir = false;
    insertForm.value.value = '';
    insertDialog.value = true;
}

function confirmInsert() {
    let prefix = insertForm.value.prefix;
    if(!JsHelper.string.endsWith(prefix,'/')){
        prefix = prefix + '/';
    }
    let name = insertForm.value.name;
    if(JsHelper.string.startsWith(name,'/')){
        name = JsHelper.string.replaceFirst(name,'/','');
    }
    let key = prefix + name;
    let value = insertForm.value.value;
    let ttl = insertForm.value.ttl;
    const params = new URLSearchParams();
    params.append('dir', insertForm.value.dir + '');
    params.append('value', value);
    params.append('ttl', ttl);
    let url = props.connect.url;
    etcd_keys_put(url,key, params)
        .then((response) => {
            search();
            insertDialog.value = false;
        })
        .catch((error) => {
            insertDialog.value = false;
            let message = error.message ||  error.response.data.message;
            ElMessage.error(message)
        });
}

function startEdit(row) {
    let key = row.key;
    insertForm.value.prefix = key.replace(row.name, '')
    insertForm.value.showName = false;
    insertForm.value.name = row.name;
    insertForm.value.showDir = false;
    insertForm.value.dir = !!row.dir;
    insertForm.value.value = row.value;
    insertDialog.value = true;
    console.log('edit', insertForm.value)
}

function startDelete(row) {
    ElMessageBox.confirm(
        'Permanently delete the node. Continue?',
        'Warning',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    )
        .then(() => {
            confirmDelete(row);
        })
        .catch(() => {
            // do nothing
        })
}

function confirmDelete(row) {
    const params = new URLSearchParams();
    params.append('recursive', true + '');
    let url = props.connect.url;
    if(row.dir){
        etcd_dir_delete(url, row.key)
            .then(res=>{
                search();
            })
            .catch(error=>{
                let message = error.response.data.message || error.message;
                ElMessage.error(message)
            })
    }else{
        etcd_keys_delete(url, row.key, params)
            .then(response => {
                search();
            })
            .catch(error=>{
                let message = error.response.data.message || error.message;
                ElMessage.error(message)
            });
    }
}

// 查询
const searchPrefix = ref(null);
function search() {
    let url = props.connect.url;
    let version = props.connect.version;
    etcd_keys_list(url).then(response => {
        console.log('数据获取成功');
        let nodes = response.data.node.nodes;
        let tree = treefy(nodes, '')
        tableData.value = tree;
        console.log('etcdcluster', tree)
    })
}

function treefy(nodes, parentPrefix) {
    if (Array.isArray(nodes)) {
        for (var i = 0; i < nodes.length; i++) {
            // nodes[i].hasChildren =false;
            // nodes[i].children = []
            let selfPath = nodes[i].key;
            nodes[i].name = selfPath.replace(parentPrefix, "");
            if (nodes[i].dir) {
                if (Array.isArray(nodes[i].nodes) && nodes[i].nodes.length > 0) {
                    nodes[i].children = nodes[i].nodes;
                    // nodes[i].hasChildren = true;
                    treefy(nodes[i].children, nodes[i].key);
                }
            }
        }
        nodes.sort((a, b) => {
            return a.name.localeCompare(b.name);
        })
    }
    console.log('nodes', nodes)
    return nodes;
}

onMounted(() => {
    search();
})

</script>
<style scoped>
.el-icon-folder-opened {
    color: #409EFF;
}

.el-icon-document {
    color: #67C23A;
}
</style>